package com.yuanqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanqi.entity.*;
import com.yuanqi.mapper.*;
import com.yuanqi.service.WareStockCountService;
import com.yuanqi.service.WareStockCountItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
* @author HP
* @description 针对表【ware_stock_count(盘点单)】的数据库操作Service实现
* @createDate 2025-08-26 14:58:48
*/
@Service
public class WareStockCountServiceImpl extends ServiceImpl<WareStockCountMapper, WareStockCount>
    implements WareStockCountService{

    @Autowired
    private WareStockCountItemMapper wareStockCountItemMapper;
    
    @Autowired
    private WareStockCountItemService wareStockCountItemService;
    
    @Autowired
    private InventoryMapper inventoryMapper;
    
    @Autowired
    private InventoryTxnMapper inventoryTxnMapper;
    
    @Autowired
    private SkuMapper skuMapper;
    
    @Autowired
    private ProductMapper productMapper;

    @Override
    public IPage<WareStockCount> listStockCounts(Integer page, Integer size, String countCode, Long warehouseId, Integer status) {
        Page<WareStockCount> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<WareStockCount> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(countCode)) {
            queryWrapper.like(WareStockCount::getCountCode, countCode);
        }
        
        if (warehouseId != null) {
            queryWrapper.eq(WareStockCount::getWarehouseId, warehouseId);
        }
        
        if (status != null) {
            queryWrapper.eq(WareStockCount::getStatus, status);
        }
        
        queryWrapper.orderByDesc(WareStockCount::getCreatedAt);
        
        return this.page(pageParam, queryWrapper);
    }

    @Override
    public Map<String, Object> getStockCountDetail(Long id) {
        // 获取盘点单主表信息
        WareStockCount stockCount = this.getById(id);
        if (stockCount == null) {
            return null;
        }
        
        // 获取盘点明细
        LambdaQueryWrapper<WareStockCountItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WareStockCountItem::getStockCountId, id);
        List<WareStockCountItem> items = wareStockCountItemMapper.selectList(queryWrapper);
        
        Map<String, Object> result = new HashMap<>();
        result.put("stockCount", stockCount);
        result.put("items", items);
        
        return result;
    }

    @Override
    @Transactional
    public boolean createStockCount(WareStockCount stockCount, List<Map<String, Object>> itemsData) {
        try {
            // 生成盘点单号
            if (!StringUtils.hasText(stockCount.getCountCode())) {
                stockCount.setCountCode("SC" + System.currentTimeMillis());
            }
            
            // 设置初始状态为新建
            stockCount.setStatus(0);
            stockCount.setCreatedAt(new Date());
            
            // 保存盘点单主表
            boolean saved = this.save(stockCount);
            if (!saved) {
                throw new RuntimeException("保存盘点单主表失败");
            }
            
            // 保存盘点明细
            List<WareStockCountItem> items = new ArrayList<>();
            for (Map<String, Object> itemData : itemsData) {
                WareStockCountItem item = new WareStockCountItem();
                item.setStockCountId(stockCount.getId());
                
                if (itemData.containsKey("locationId") && itemData.get("locationId") != null && !itemData.get("locationId").toString().isEmpty()) {
                    item.setLocationId(Long.valueOf(itemData.get("locationId").toString()));
                } else {
                    item.setLocationId(1L); // 默认库位
                }
                
                if (itemData.containsKey("skuId")) {
                    item.setSkuId(Long.valueOf(itemData.get("skuId").toString()));
                }
                
                if (itemData.containsKey("batchNo")) {
                    item.setBatchNo(itemData.get("batchNo").toString());
                }
                
                if (itemData.containsKey("systemQty") && itemData.get("systemQty") != null) {
                    item.setSystemQty(new BigDecimal(itemData.get("systemQty").toString()));
                } else {
                    item.setSystemQty(BigDecimal.ZERO);
                }
                
                if (itemData.containsKey("countQty") && itemData.get("countQty") != null) {
                    item.setCountQty(new BigDecimal(itemData.get("countQty").toString()));
                } else {
                    item.setCountQty(BigDecimal.ZERO);
                }
                
                // 计算差异数量
                item.setDiffQty(item.getCountQty().subtract(item.getSystemQty()));
                
                items.add(item);
            }
            
            return wareStockCountItemService.saveBatch(items);
        } catch (Exception e) {
            throw new RuntimeException("创建盘点单失败: " + e.getMessage(), e);
        }
    }

    @Override
    @Transactional
    public boolean submitStockCount(Long id) {
        WareStockCount stockCount = this.getById(id);
        if (stockCount == null || (stockCount.getStatus() != 0 && stockCount.getStatus() != 4)) {
            return false;
        }
        
        // 更新状态为进行中
        stockCount.setStatus(1);
        return this.updateById(stockCount);
    }

    @Override
    @Transactional
    public boolean approveStockCount(Long id) {
        WareStockCount stockCount = this.getById(id);
        if (stockCount == null || stockCount.getStatus() != 1) {
            return false;
        }

        // 获取盘点明细并执行库存调整
        LambdaQueryWrapper<WareStockCountItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WareStockCountItem::getStockCountId, id);
        List<WareStockCountItem> items = wareStockCountItemMapper.selectList(queryWrapper);

        // 处理库存调整 - 审核通过时直接用盘点数量覆盖系统数量
        for (WareStockCountItem item : items) {
            // 查询库存记录
            LambdaQueryWrapper<Inventory> inventoryQuery = new LambdaQueryWrapper<>();
            inventoryQuery.eq(Inventory::getSkuId, item.getSkuId())
                    .eq(Inventory::getWarehouseId, stockCount.getWarehouseId())
                    .eq(Inventory::getLocationId, item.getLocationId());

            if (StringUtils.hasText(item.getBatchNo())) {
                inventoryQuery.eq(Inventory::getBatchNo, item.getBatchNo());
            }

            Inventory inventory = inventoryMapper.selectOne(inventoryQuery);
            
            if (inventory != null) {
                // 直接用盘点数量覆盖库存数量
                BigDecimal oldQty = inventory.getOnHandQty();
                inventory.setOnHandQty(item.getCountQty());
                inventory.setAvailableQty(item.getCountQty());
                inventory.setUpdatedAt(new Date());
                inventoryMapper.updateById(inventory);
                
                // 创建库存调整事务记录
                InventoryTxn txn = new InventoryTxn();
                txn.setWarehouseId(stockCount.getWarehouseId());
                txn.setLocationId(item.getLocationId());
                txn.setSkuId(item.getSkuId());
                txn.setBatchNo(item.getBatchNo());
                txn.setQty(item.getCountQty().subtract(oldQty)); // 实际调整数量
                txn.setTxnType("ADJ"); // 盘点调整
                txn.setReferenceTable("ware_stock_count");
                txn.setReferenceId(stockCount.getId());
                txn.setRemark("盘点审核通过，库存调整: " + stockCount.getCountCode());
                txn.setTxnCode("ADJ" + System.currentTimeMillis());
                inventoryTxnMapper.insert(txn);
            }
        }
        
        // 更新状态为已审核
        stockCount.setStatus(2);
        stockCount.setApprovedAt(new Date());
        return this.updateById(stockCount);
    }
    
    /**
     * 驳回盘点单
     * @param id 盘点单ID
     * @return 是否成功
     */
    @Transactional
    public boolean rejectStockCount(Long id) {
        WareStockCount stockCount = this.getById(id);
        if (stockCount == null || stockCount.getStatus() != 1) {
            return false;
        }
        
        // 更新状态为已驳回
        stockCount.setStatus(4);
        return this.updateById(stockCount);
    }

    @Override
    @Transactional
    public boolean updateStockCount(WareStockCount stockCount, List<Map<String, Object>> itemsData) {
        // 检查盘点单是否存在且状态允许修改
        WareStockCount existingStockCount = this.getById(stockCount.getId());
        if (existingStockCount == null || existingStockCount.getStatus() != 4) {
            return false; // 只有驳回状态的盘点单才能修改
        }

        // 更新盘点单基本信息
        boolean updateResult = this.updateById(stockCount);
        if (!updateResult) {
            return false;
        }

        // 删除原有的盘点单明细
        LambdaQueryWrapper<WareStockCountItem> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(WareStockCountItem::getStockCountId, stockCount.getId());
        wareStockCountItemMapper.delete(deleteWrapper);

        // 添加新的盘点单明细
        for (Map<String, Object> itemData : itemsData) {
            WareStockCountItem item = new WareStockCountItem();
            item.setStockCountId(stockCount.getId());
            item.setSkuId(Long.valueOf(itemData.get("skuId").toString()));
            item.setSystemQty(new BigDecimal(itemData.get("systemQty").toString()));
            item.setCountQty(new BigDecimal(itemData.get("countQty").toString()));
            item.setDiffQty(new BigDecimal(itemData.get("diffQty").toString()));
            
            // 设置默认库位（可以根据业务需求调整）
            item.setLocationId(1L); // 默认库位ID，实际应该根据业务逻辑设置
            
            wareStockCountItemMapper.insert(item);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean executeStockCount(Long id) {
        WareStockCount stockCount = this.getById(id);
        if (stockCount == null || stockCount.getStatus() != 2) {
            return false;
        }

        // 获取盘点明细
        LambdaQueryWrapper<WareStockCountItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WareStockCountItem::getStockCountId, id);
        List<WareStockCountItem> items = wareStockCountItemMapper.selectList(queryWrapper);

        // 处理库存调整
        for (WareStockCountItem item : items) {
            if (item.getDiffQty().compareTo(BigDecimal.ZERO) == 0) {
                continue; // 无差异，跳过
            }
            
            // 查询库存记录
            LambdaQueryWrapper<Inventory> inventoryQuery = new LambdaQueryWrapper<>();
            inventoryQuery.eq(Inventory::getSkuId, item.getSkuId())
                    .eq(Inventory::getWarehouseId, stockCount.getWarehouseId())
                    .eq(Inventory::getLocationId, item.getLocationId());

            if (StringUtils.hasText(item.getBatchNo())) {
                inventoryQuery.eq(Inventory::getBatchNo, item.getBatchNo());
            }

            Inventory inventory = inventoryMapper.selectOne(inventoryQuery);
            
            if (inventory != null) {
                // 调整库存数量为盘点数量
                inventory.setOnHandQty(item.getCountQty());
                inventory.setAvailableQty(item.getCountQty());
                inventory.setUpdatedAt(new Date());
                inventoryMapper.updateById(inventory);
                
                // 创建库存调整事务记录
                InventoryTxn txn = new InventoryTxn();
                txn.setWarehouseId(stockCount.getWarehouseId());
                txn.setLocationId(item.getLocationId());
                txn.setSkuId(item.getSkuId());
                txn.setBatchNo(item.getBatchNo());
                txn.setQty(item.getDiffQty()); // 差异数量
                txn.setTxnType("ADJ"); // 调整
                txn.setReferenceTable("ware_stock_count");
                txn.setReferenceId(stockCount.getId());
                txn.setRemark("库存盘点调整: " + stockCount.getCountCode());
                txn.setTxnCode("ADJ" + System.currentTimeMillis());
                inventoryTxnMapper.insert(txn);
            }
        }

        // 更新盘点单状态为已完成
        stockCount.setStatus(3);
        return this.updateById(stockCount);
    }

    @Override
    @Transactional
    public Long generateStockCountTask(Long warehouseId) {
        // 创建盘点单
        WareStockCount stockCount = new WareStockCount();
        stockCount.setCountCode("SC" + System.currentTimeMillis());
        stockCount.setWarehouseId(warehouseId);
        stockCount.setStatus(0);
        stockCount.setCreatedBy("系统");
        stockCount.setCreatedAt(new Date());
        
        this.save(stockCount);
        
        // 查询该仓库的所有库存
        LambdaQueryWrapper<Inventory> inventoryQuery = new LambdaQueryWrapper<>();
        inventoryQuery.eq(Inventory::getWarehouseId, warehouseId);
        List<Inventory> inventories = inventoryMapper.selectList(inventoryQuery);
        
        // 生成盘点明细
        List<WareStockCountItem> items = new ArrayList<>();
        for (Inventory inv : inventories) {
            WareStockCountItem item = new WareStockCountItem();
            item.setStockCountId(stockCount.getId());
            item.setLocationId(inv.getLocationId());
            item.setSkuId(inv.getSkuId());
            item.setBatchNo(inv.getBatchNo());
            item.setSystemQty(inv.getOnHandQty()); // 系统库存数量
            item.setCountQty(BigDecimal.ZERO); // 待盘点
            item.setDiffQty(BigDecimal.ZERO.subtract(inv.getOnHandQty())); // 初始差异
            
            items.add(item);
        }
        
        wareStockCountItemService.saveBatch(items);
        
        return stockCount.getId();
    }
}




